<?php
namespace App\Http\Controllers\Admin\Users;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\UsersRepository;
use App\Repositories\UsersMenusRepository as UsersMenusRepository;
use App\Repositories\UsersRolesRepository;
use Log;
use Storage;
use Illuminate\Support\Facades\DB;
use App\Repositories\UsersInRolesRepository;
/**
 * 后台的用户相关的接口
 */
class IndexController extends Controller
{

	public function __construct()
	{
		$this->middleware('auth:users', ['except' => ['check']]);
		//$this->middleware('UsersPermissions');
	}
	public function GetMenus(UsersMenusRepository $UsersMenusRepository, Request $request)
	{
		$user = auth('users')->user();
		//$this->list = $UsersMenusRepository->GetMenus($user->ID);
		$this->list=$UsersMenusRepository->GetMenu();
		$data = $this->GetMenuList(0);
		 
		return response()->json(['code' => 0, 'data' => $data, 'type' => 'adminMenu']);
	}
	protected function GetMenuList($ParentID)
	{
		$list = [];
		foreach ($this->list as $item) {
			if ($item->ParentID == $ParentID) {
				$list[] = [
					"path" => $item->Path,
					"name" => $item->Path,
					"component" => $item->Component,
					"redirect" => $item->Redirect,
					"props" => true,
					"meta" => [
						"title" => "message.menus." . $item->LangKey,
						"isLink" => $item->IsLink == 1 ? true : "",
						"isKeepAlive" => false,
						"isAffix" => false,
						"isIframe" => false,
						"roles" => ["admin", "common"],
						"icon" => $item->Ico,
						"isHide" => $item->IsHide == 1 ? true : ""
					],
					'children' => $this->GetMenuList($item->ID)
				];
			}
		}
		return $list;
	}
	public function GetList(UsersRepository $UsersRepository, Request $request)
	{
		$pagesize = $request->input('pagesize', '25');
		$kw = $request->input('kw', '');
		$result = $UsersRepository->GetList(addslashes($kw), [], [], $pagesize, ['CreateTime' => 'desc'], ['ID',
    									 'Number',
    									 'Name',
    									 'Avatar',
    									 'AccountName',
    									 'MobileTelephone',
    									 'Email',
    									 'QQ',
    									 'Wechat',
    									 'LoginCount',
    									 'LastIp',
    									 'LoginTime',
    									 'Roles',
    									 'Status',
    									 'CreateTime']);
		return response()->json(['code' => 0, 'result' => $result]);
	}
	public function Check()
	{
		return response()->json(['auth' => auth('users')->check()]);

	}
	/**
	 * Refresh a token.
	 * 刷新token，如果开启黑名单，以前的token便会失效。
	 * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function Refresh()
	{
		
		return $this->respondWithToken(auth('users')->refresh());
	}
	/**
	 *  创建账号
	 */
	public function Create(UsersRepository $UsersRepository, Request $request)
	{

		$Users = [
			'ID' => $this->nextid(),
			'Number' => $UsersRepository->NextNumber(6),
			'CreateTime' => time(),
			'Name' => trim($request->input('Name')),
			'AccountName' => trim($request->input('AccountName')),
			'Password' => bcrypt(trim($request->input('Password'))),
			'MobileTelephone' => trim($request->input('MobileTelephone')),
			'Email' => trim($request->input('Email')),
			'QQ' => trim($request->input('QQ')),
			'Wechat' => trim($request->input('Wechat')),
			'Avatar' => ''
		];

		if (!$UsersRepository->existsWhere(['AccountName' => $Users['AccountName']])) {
			if ($UsersRepository->create($Users)) {
				return response()->json(['code' => 0, 'message' => '用户账号操作成功！']);
			}
			else {
				return response()->json(['code' => 1, 'message' => '抱歉，创建用户失败！']);
			}
		}
		else {
			return response()->json(['code' => 1, 'message' => '账号名已经被占用']);
		}
	}
	public function SetInfo(UsersRepository $UsersRepository, Request $request)
	{
		$requestData = [
			'AccountName' => trim($request->input('AccountName')),
			'Name' => trim($request->input('Name')),
			'MobileTelephone' => trim($request->input('MobileTelephone')),
			'Email' => trim($request->input('Email')),
			'QQ' => trim($request->input('QQ')),
			'Wechat' => trim($request->input('Wechat')),
		];
		
		$ID = $request->input('ID');
		
		$model = $UsersRepository->find($ID);
		if(!empty($model)){
			$model->update($requestData);
			return response()->json(['code' => 0, 'message' => '完成资料设置']);
		}else{
			return response()->json(['code' => 1, 'message' => '无法查找到匹配资料！']);
			}

		
	}
	public function Enable(UsersRepository $UsersRepository, Request $request)
	{
		$ID = $request->input('ID');
		$model = $UsersRepository->find($ID);
		if ($model->update(['Status' => 0])) {
			return response()->json(['code' => 0, 'message' => '账号启用成功']);
		}
		else {
			return response()->json(['code' => 1, 'message' => '账号启用失败']);
		}
	}
	public function Disable(UsersRepository $UsersRepository, Request $request)
	{
		$ID = $request->input('ID');
		$model = $UsersRepository->find($ID);

		if ($model->update(['Status' => 1])) {
			return response()->json(['code' => 0, 'message' => '账号禁用成功']);
		}
		else {
			return response()->json(['code' => 1, 'message' => '账号禁用失败']);
		}
	}
	public function Exist(UsersRepository $UsersRepository, Request $request)
	{
		$AccountName = trim($request->input('AccountName'));
		$ID = trim($request->input('ID'));
		return response()->json(['code' => 0, 'result' => $UsersRepository->existsWhere([['AccountName', '=', $AccountName], ['ID', '<>', $ID]])]);
	}
	 
	/*
	 *  设置用户头像
	 */
	public function UploadUsersFace(Request $request, UsersRepository $UsersRepository)
	{

		$ID = $request->input('ID');
		if ($request->hasFile('file')) {
			$user = $UsersRepository->find($ID);
			$file = $request->file('file');
			// $originalName = $file->getClientOriginalName(); // 文件原名
			$ext = $file->getClientOriginalExtension(); // 扩展名
			$realPath = $file->getRealPath(); //临时文件的绝对路径
			$type = $file->getClientMimeType(); // image/jpeg
			// 上传文件
			$filename = uniqid() . '.' . $ext;
			//Log::info($filename);
			if (in_array(strtolower($file->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
				// 使用我们新建的uploads本地存储空间（目录）
				//这里的upload是配置文件的名称
				$bool = Storage::disk('oss')->put("/avatar/users/" . $filename, file_get_contents($realPath));
				//判断是否创建成功
				if (!$bool) {
					return response()->json(['code' => 1, 'message' => '头像上传失败']);
				}
				else {
					if (trim($user->Avatar) != '') {
						//删除旧的头像
						Storage::disk('oss')->delete("/avatar/users/" . $user->Avatar);
					}
					$UsersRepository->update(['Avatar' => $filename], $ID);
					return response()->json(['code' => 0, 'message' => '头像上传成功', 'result' => $filename]);
				}
			}
			else {
				return response()->json(['code' => 1, 'message' => '请选择图片文件']);
			}
		}


	}
 
	/**
	* 管理员设置密码
	*/
	public function SetPass(UsersRepository $UsersRepository, Request $request)
	{
		$ID = $request->input('ID');
		$model = $UsersRepository->findBy('ID', $ID);
		if ($UsersRepository->update(['Password' => bcrypt(trim($request->input('Password')))], $ID)) {
			return response()->json(['code' => 0, 'message' => '设置密码成功']);
		}
		else {
			return response()->json(['code' => 1, 'message' => '设置密码失败']);
		}

	}
	public function GetAllUsersRolesANDUserID(UsersRolesRepository $UsersRolesRepository, UsersRepository $UsersRepository, Request $request)
	{
		$ID = $request->input('ID');
		$model = $UsersRepository->findBy('ID', $ID);
		if ($model) {
			$result = $UsersRolesRepository->GetListANDUserID($model->ID);
			return response()->json(['code' => 0, 'result' => $result]);
		}
		return response()->json(['code' => 1, 'message' => '无法完成请求']);
	}
	public function SaveRoles(UsersInRolesRepository $UsersInRolesRepository, UsersRepository $UsersRepository, UsersRolesRepository $UsersRolesRepository,Request $request)
	{
		$ID = $request->input('ID');
		$model = $UsersRepository->findBy('ID', $ID);
		if ($model) {
			$Roles = $request->input('Roles');
			$roles = explode(',', $Roles);

			DB::beginTransaction();
			try {
				$UsersInRolesRepository->DeleteByUsersID($model->ID);
				$UsersRoles=[];
				foreach ($roles as $RolesID) {
					if ($RolesID != '') {
						$UsersInRolesRepository->create(['RolesID' => $RolesID, 'UsersID' => $model->ID]);
						$Roles=$UsersRolesRepository->find($RolesID);
						if(!empty($Roles))
						{
							$UsersRoles[]=$Roles->Name;
						}
					}
				}
				$model->Roles=join(",",$UsersRoles);
				$model->save();
				DB::commit();
				return response()->json(['code' => 0, 'message' => '用户角色设置成功']);
			}
			catch (Exception $e) {
				DB::rollBack();
				Log::error($e->getMessage());
				return ['code' => 1, 'message' => '执行查询失败，请查看日志！'];
			}

		}
		return response()->json(['code' => 1, 'message' => '无法完成请求']);
	}
	protected function respondWithToken($token)
	{
     $user=auth('users')->user();
     $user->Avatar=$user->Avatar==''?$userInfo->Avatar:$this->ToImageURL('/avatar/users/'.$user->Avatar);
		return response()->json([
			'code' => 0,
			'access_token' => $token,
			'token_type' => 'bearer',
			'expires_in' => auth('users')->factory()->getTTL() * 60,
			'result' => $user,
		]);
	}
}